package com.sheng.leetcode.year2022.month08.day17;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liusheng
 * @date 2022/08/17
 *
 * 1302. 层数最深叶子节点的和
 *
 * 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和 。
 *
 * 示例 1：
 * 输入：root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
 * 输出：15
 *
 * 示例 2：
 * 输入：root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
 * 输出：19
 *
 * 提示：
 *
 * 树中节点数目在范围 [1, 104] 之间。
 * 1 <= Node.val <= 100
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode.cn/problems/deepest-leaves-sum
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LeetCode1302 {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(2);
        TreeNode left1 = new TreeNode(4);
        left1.left = new TreeNode(7);
        left.left = left1;
        left.right = new TreeNode(5);
        TreeNode right = new TreeNode(3);
        TreeNode right1 = new TreeNode(6);
        right1.right = new TreeNode(8);
        right.right = right1;
        root.left = left;
        root.right = right;
        System.out.println(new Solution().deepestLeavesSum(root));
    }
}

//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int deepestLeavesSum(TreeNode root) {
        //层序遍历
        List<TreeNode> treeNodeList = new ArrayList<>();
        if (root != null) {
            treeNodeList.add(root);
        }
        return bfs(treeNodeList);
    }

    public int bfs(List<TreeNode> treeNodeList) {
        List<TreeNode> treeNodes = new ArrayList<>();
        int sum = 0;
        for (TreeNode treeNode : treeNodeList) {
            if (treeNode.left != null) {
                treeNodes.add(treeNode.left);
            }
            if (treeNode.right != null) {
                treeNodes.add(treeNode.right);
            }
            sum += treeNode.val;
        }
        if (treeNodes.size() != 0) {
            return bfs(treeNodes);
        } else {
            return sum;
        }
    }
}
